#include "tabview.hpp"
#include <utility>
#include "content/bindable.hpp"
#include "content/data_provider.hpp"
#include "content/view_base.hpp"
#include "imgui.h"
#include "ui/container/tabview.hpp"

void tab_view::bind(bindable_base *data) {
    for (auto &x: tabs_) {
        x.second->attach(data);
    }
}

void tab_view::init_content(const xml_node &node)
{
    auto item_node = node.child("tab");
    while(item_node) {
        std::string tab_name = item_node.attribute("name").as_string();
        data_provider_p content = create_data(item_node.attribute("view").as_string(), ui);
        if (content)
            tabs_.emplace_back(std::make_pair(tab_name, content));
        else
            L_ERROR("error parse tab %s", tab_name.c_str());
        item_node = item_node.next_sibling("tab");
    }
}

void tab_view::draw_self()
{
    ImGui::PushID(this);
    open_ = ImGui::BeginTabBar("##TabBar");
}

void tab_view::draw_children()
{
    if (open_) {
        for (auto &x: tabs_) {
            if (ImGui::BeginTabItem(x.first.c_str())) {
                ui_view *view = x.second->get_ui();
                view->draw();
                ImGui::EndTabItem();
            }
        }
        ImGui::EndTabBar();
    }
    ImGui::PopID();
}